#!/usr/bin/perl -w
# geocoder.cgi - Simple Geocoder powered by Google Maps
# Hirotaka Ogawa (hirotaka.ogawa at gmail.com)

use strict;
use CGI;
use LWP::Simple;
use URI::Escape;

my $url;

my $q = CGI->new;
$q->charset('utf-8');
$url = $q->url;
my $address = $q->param('address') || '';
$address =~ s/^\s+//;
$address =~ s/\s+$//;
if ($address) {
    my $res = get("http://maps.google.co.jp/maps?q=" . uri_escape($address) .
		  "&output=kml");
    if ($res) {
	my ($addr) = $res =~ /address>([^<]*)/is;
	$addr =~ s/^（日本）//;
	$addr =~ s/^日本//;
	my ($lon, $lat, $alt) = $res =~ /coordinates>(.*),(.*),(.*)</is;
	show_coords($addr, $lat, $lon);
    } else {
	show_form($address);
    }
} else {
    show_form();
}

sub show_form {
    my $address = shift || '';
    print "Content-type: text/html\n\n";
    print <<HTML;
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Simple geocoder powered by Google Maps</title>
    <style>h1 { font-size: 14px; } body, input { font-size: 12px; font-family: verdana,arial,sans-serif; }</style>
  </head>
  <body>
    <h1>Simple geocoder powered by Google Maps</h1>
    <form action="$url">
      <label>Address:</label>
      <input name="address" type="text" size="80" value="$address" />
      <input type="submit" value="Get geocode!" />
    </form>
  </body>
</html>
HTML
}

sub show_coords {
    my ($addr, $lat, $lon) = @_;
    print "Content-type: text/xml\n\n";
    print <<RDF;
<?xml version="1.0" encoding="utf-8"?>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
         xmlns:dc="http://purl.org/dc/elements/1.1/"
         xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
  <geo:Point>
    <dc:description>$addr</dc:description>
    <geo:lat>$lat</geo:lat>
    <geo:long>$lon</geo:long>
  </geo:Point>
</rdf:RDF>
RDF
}
